package net.beyondts.mplug;

import net.beyondts.mplug.utils.BeanFactory;
import net.beyondts.mplug.utils.Transformer;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * Created by blazecrystal on 2019-1-16.
 *
 * @author blazecrystal
 */
public final class PluginsUtils {
    private static Logger LOGGER = LoggerFactory.getLogger(PluginsUtils.class);

    /**
     * Get plugins base directory configed in System properties.
     * @return String plugins' base directory's absolute path
     * @throws IOException ...
     */
    public static String getPluginsDir() throws IOException {
        String pluginsDir = System.getProperty("plugins.dir");
        if (StringUtils.isBlank(pluginsDir)) {
            pluginsDir = Transformer.toLocalFilePathWithSeperatorEnd(System.getProperty("user.dir")) + "plugins";
            LOGGER.debug("system property \"plugins.dir\" not found, use \"user.dir\" instead");
        }
        File file = new File(pluginsDir);
        if (!file.exists() || !file.isDirectory()) {
            throw new IOException(pluginsDir + " does not exist or is not a directory");
        }
        return file.getAbsolutePath() + File.separator;
    }

    /**
     * Get the instance of a class which cantains plugin methods.
     *     1. get instance from Spring Context.
     *     2. if not found in spring, create one use default no args constructor.
     * @param clazz Class&lt;?&gt; the class to be instantiated
     * @return Object the instance of given class
     * @throws IllegalAccessException ...
     * @throws InstantiationException ...
     */
    public static Object getPluginClassInstance(Class<?> clazz) throws IllegalAccessException, InstantiationException {
        Object target = null;
        try {
            target = BeanFactory.getBean(clazz);
            LOGGER.debug("found instance for type \"" + clazz.getName() + "\" in spring context");
        } catch (Exception e) {
            target = clazz.newInstance();  // if not found bean from spring context, than use default constructor to create one
            LOGGER.debug("create new instance for type \"" + clazz.getName() + "\" by default no-args constructor");
        }
        return target;
    }
}
